/*
 * Created on 2005-9-28
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.zsoft.webmail.http;

/**
 * @author zhaozb
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
import java.net.*;
import java.util.*;
import java.io.*;
import javax.swing.*;

import com.zsoft.webmail.Application;

public class HttpUtils {
  private JSlider jSlider1 = new JSlider();


  public static HttpURLConnection getConnection( String url,Hashtable p ) throws Exception {
    return getConnection(url,p,"POST");
  }
  public static HttpURLConnection getConnection( String url,Hashtable p ,String method ) throws Exception {

    URL _url = new URL( url );

    HttpURLConnection connection = (HttpURLConnection) _url.openConnection();

    connection.setRequestMethod(method);

    connection.setDoInput(true);

    connection.setDoOutput(true);

    connection.setUseCaches(false);

    if(p!=null){
      Enumeration e=p.keys();
      while(e.hasMoreElements()){
        String key=(String)e.nextElement();
        String value=(String)p.get(key);
        connection.setRequestProperty(key,value);
      }
    }

    connection.connect();

    return connection;
  }
  public static String getResponse( HttpURLConnection connection) throws Exception {
    return getResponse(connection,Application.getProperty("defaultInputCharset"));
  }
  public static String getResponse( HttpURLConnection connection,String charset) throws Exception {


    //String contentType = connection.getContentType();
    //if(contentType==null)contentType="";
    //contentType=contentType.toLowerCase().trim();
    //Object o=connection.getResponseMessage();
    //String s=connection.getResponseMessage();
    //connection.getContent();

    int responseCode = connection.getResponseCode();

    //if ( contentType.startsWith("text/html") ) {
    if ( responseCode==200) {
      InputStream dis =null;
      String c=connection.getContentEncoding();
      if(c!=null && c.equalsIgnoreCase("gzip")){
        dis=new java.util.zip.GZIPInputStream(connection.getInputStream());
      }else{
        dis = connection.getInputStream();
      }

      ByteArrayOutputStream bytearrayoutputstream;

      bytearrayoutputstream = new ByteArrayOutputStream();


      try{
      int blockSize = 4096;

      byte buf[] = new byte[blockSize];
      int bytesRead = 0;
      while((bytesRead = dis.read(buf)) != -1){
        //sbf.append(new String(buf, 0, bytesRead));
        bytearrayoutputstream.write(buf,0,bytesRead);
      }

      }catch(Exception ex){
      }finally{
        dis.close();
      }
      //return sbf.toString();
      return new String(bytearrayoutputstream.toByteArray(),charset);





    } else {
      // must have returned an error, determine the response details


      String responseMessage = connection.getResponseMessage();

      throw new Exception(responseCode+" "+responseMessage);

    }


  }
  public static void sendRequest( HttpURLConnection connection,  String[]  params ) throws Exception {


  if(connection.getRequestMethod().endsWith("POST")){

    // get an output stream from the connection
    OutputStream cos = connection.getOutputStream();
    PrintWriter cosOut = new PrintWriter(cos);



    // write the parameters to the output stream
    StringBuffer buf = new StringBuffer();
    if ( params != null ) {
      for(int i=0;i<params.length;i++){
        if ( buf != null && buf.length()>0 ) buf.append("&");
          buf.append(params[i]);
      }

      //System.out.println(buf.toString());
      cosOut.print(buf.toString());
    }

    // close the output stream
    cosOut.close();
    }

    return;
  }
  public static String encodeURL(String uri)
  {
    StringBuffer cb = new StringBuffer();

    for (int i = 0; i < uri.length(); i++) {
      char ch = uri.charAt(i);

      switch (ch) {
      case '<':
      case '>':
      case ' ':
      case '%':
      case '\'':
      case '\"':
        cb.append('%');
        cb.append(encodeHex(ch >> 4));
        cb.append(encodeHex(ch));
        break;

      default:
        cb.append(ch);
      }
    }

    return cb.toString();
  }

  public static String byteToHex(int b)
  {
    StringBuffer cb = new StringBuffer();

    cb.append(encodeHex((b & 0xf0) >> 4));
    cb.append(encodeHex(b & 0xf));

    return cb.toString();
  }

  public static char encodeHex(int ch)
  {
    ch &= 0xf;

    if (ch < 10)
      return (char) (ch + '0');
    else
      return (char) (ch + 'a' - 10);
  }

  public HttpUtils() {
    try {
      jbInit();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
  private void jbInit() throws Exception {
  }
}